package com.appspot.smartgan.adapter;

import java.util.LinkedList;
import java.util.List;

import com.appspot.smartgan.ChildActivity;
import com.appspot.smartgan.R;
import com.appspot.smartgan.util.ContactListPerson;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class ContactListAdapter extends ArrayAdapter<ContactListPerson> {
	
	private final List<ContactListPerson> people;
	private final Context context;
	private final LayoutInflater inflater;
	
	public ContactListAdapter(Context context, List<ContactListPerson> people) {
		super(context, R.layout.contact_list_row, people);
		
		this.inflater = LayoutInflater.from(context);
		this.context = context;
		if (people == null) {
			this.people = new LinkedList<ContactListPerson>();
		} else {
			this.people = people;
		}
	}
	
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.contact_list_row, null);
			holder = new ViewHolder(convertView);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		
		ContactListPerson person = people.get(position);
		holder.nameTextView.setText(person.getName());
		holder.phoneTextView.setText(person.getPhoneNumber());
		
		convertView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				ChildActivity activity = (ChildActivity) context;
				activity.displayContactListDetails(people.get(position));
			}
		});
		
		return convertView;
	}
	
	static class ViewHolder {
		TextView nameTextView;
		TextView phoneTextView;
		
		ViewHolder(View view) {
			nameTextView = 
					(TextView) view.findViewById(R.id.contactListNameTextView);
			phoneTextView = 
					(TextView) view.findViewById(R.id.contactListPhoneNumberTextView);
		}
	}
	
}
